package kr.pe.johnkim.sendme.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.google.android.gcm.GCMRegistrar;

import kr.pe.johnkim.sendme.activity.R;
import kr.pe.johnkim.sendme.provider.SendMeFriend;
import kr.pe.johnkim.sendme.provider.SendMeInstall;
import kr.pe.johnkim.sendme.provider.SendMeVoice;
import kr.pe.johnkim.sendme.rest.SendMeAudioMessageRest;
import kr.pe.johnkim.sendme.rest.SendMeInstallRest;
import kr.pe.johnkim.sendme.util.SendMeActivityManager;
import kr.pe.johnkim.sendme.util.SendMeCommon;
import kr.pe.johnkim.sendme.util.SendMeConstant;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;
import android.view.Window;

/**
 * 인트로 화면 액티비티 클래스 이다.
 * 
 * @author johnkim
 *
 */
public class SendMeIntroActivity extends Activity {

	public static String TAG = SendMeIntroActivity.class.getSimpleName();

	private SendMeActivityManager sendMeActivityManager = SendMeActivityManager.getInstance();

	private Handler mhandler = new Handler();

	// 대기 시간.
	private long INTRO_DELAY_TIME = 2000;

	// 마스터 암호.
	private String MASTER_PASSWORD = "";

	// 퍼블릭 암호.
	private String PUBLIC_PASSWORD = "";

	// 기능 모드.(MASTER/PUBLIC)
	private String FUNCTION_MODE = "";

	// Push id for GCM.
	private String PUSH_ID = "";

	// 사용자 휴대 전화번호.
	private String PHONE_NUMBER = "";

	// 전화번호 부
	List<SendMeInstall> sendMeInstallList;

	// 전화번호부 목록을 서버로 전달한다
	private static final int THREAD_UPDATE_INSTALL = 113;		


	// 암호 설정 액티비티 요청 코드
	private static final int PASSWORD_ACTIVITY_CODE = 135;		

	// 전달할 동작 코드의 액션
	private static final int ACTION_CODE_SOME_KEY_CHECK = 201;			//  키 확인 (마스터 또는 퍼블릭)
	private static final int ACTION_CODE_MASTER_KEY_CHECK  = 212;		//  마스터 키 확인
	private static final int ACTION_CODE_PUBLIC_KEY_CHECK  = 222;		//  퍼블릭 키 확인

	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// 화면 상단의 타이틀바를 제거 한다.
		requestWindowFeature(Window.FEATURE_NO_TITLE );

		setContentView(R.layout.activity_send_me_intro);

//		// 에러가 나므로 일단 무조건 실행.
//		Log.e(TAG,"sendMeActivityManager.getAcArrayListCount:"+sendMeActivityManager.getAcArrayListCount());
//		if(sendMeActivityManager.getAcArrayListCount() >0){
////			Log.d(TAG,"getTitle::" + sendMeActivityManager.getAcArrayList().get(0).getTitle());
//			finish();
//		}else{
			
			sendMeActivityManager.addActivity(this);
			
			
			// GCM 정보를 가져 온다. 
			final String pushId = GCMRegistrar.getRegistrationId(this);
			if("".equals(pushId) || pushId == null) {
				GCMRegistrar.register(this, SendMeConstant.PROJECT_NUMBER);
			} else {
				PUSH_ID = pushId;
				Log.i(TAG, "pushId is already exist : " + PUSH_ID);
			}
			GCMRegistrar.register(this, SendMeConstant.PROJECT_NUMBER);

			mhandler.postDelayed(mRunnable, INTRO_DELAY_TIME);
//		}
	}

	/**
	 * 필요한 핸들러를 등록해서 사용한다.
	 */
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what) {
			// 전화번호부 목록을 서버로 전달하고 액티비티를 종료한다
			case THREAD_UPDATE_INSTALL : 
				threadUpdateInstallAndFinish();
				break;
			}
		}
	};

	/**
	 * GCM 리시버를 해제한다. 
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		GCMRegistrar.onDestroy(this);		 
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.send_me_intro, menu);
		return true;
	}

	Runnable mRunnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			confirmNotification();

			// 비가입 사용자임. 가입화면으로 이동
			if(("").equals(PHONE_NUMBER)) {
				Intent i = new Intent(SendMeIntroActivity.this, SendMePolicyActivity.class);
				startActivity(i);
				finish();
			}else{

				// 암호 있음. 확인 받음.
				if((!("").equals(MASTER_PASSWORD)) || (!("").equals(PUBLIC_PASSWORD))) {
					Intent i = new Intent(SendMeIntroActivity.this, SendMePasswordActivity.class);

					Intent passwordActivity = new Intent(SendMeIntroActivity.this, SendMePasswordActivity.class);
					passwordActivity.putExtra("ACTION_CODE", ACTION_CODE_SOME_KEY_CHECK);
					startActivityForResult(passwordActivity, PASSWORD_ACTIVITY_CODE);
				// 암호 없음	
				} else {
					
					savePreferenceFunctionMode("");
					
					Intent i = new Intent(SendMeIntroActivity.this, SendMeMainActivity.class);
					startActivity(i);

					// 전화번호부를 가져와서 서버로 전송하고 종료
					mHandler.sendMessage(mHandler.obtainMessage(THREAD_UPDATE_INSTALL));
				}
			}
		}
	};

	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 서버 통신
	/**
	 * 전화번호부에 있는 데이터를 읽어서 서버로 전송한다. (설치한 친구 목록을 업데이트 한다.)
	 *  이후 액티비티를 종료한다
	 *   서버로 전번 보내는 부분이라서 sendMeCommon.selectPhoneBookAddress 호출함
	 */
	public void threadUpdateInstallAndFinish() {

		Thread thread = new Thread(new Runnable() {

			public void run() {
				// TODO Auto-generated method stub

				
				SendMeCommon sendMeCommon = new SendMeCommon();
				
				ArrayList<SendMeFriend> phoneBookAddress = sendMeCommon.selectPhoneBookAddress(returnThis());  
				
				sendMeInstallList = new ArrayList<SendMeInstall>();
				String nowTime = sendMeCommon.getCurrentDate();
				
				for(int i=0; i<phoneBookAddress.size(); i++){
					
					SendMeInstall sendMeInstall = new SendMeInstall();
					sendMeInstall.setPhoneNumber(phoneBookAddress.get(i).getPhoneNumber());
					sendMeInstall.setActivateYn("Y");
					sendMeInstall.setModifyDate(nowTime);
					sendMeInstall.setRegisterDate(nowTime);
					sendMeInstall.setSendMeMemberPhoneNumber(PHONE_NUMBER);

					sendMeInstallList.add(sendMeInstall);

				}
				SendMeInstallRest sendMeInstallRest = new SendMeInstallRest();
				sendMeInstallRest.updateInstall(sendMeInstallList);		// 테스트를 위해 잠시 주석 ### 
				finish();
			}
		});
		thread.start();
	}

	public Context returnThis(){
		return this;
	}
	
	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Bundle extraBundle;
		if( requestCode == PASSWORD_ACTIVITY_CODE ) {
			if(resultCode == Activity.RESULT_OK){		// 정상 반환시.

				Log.d(TAG,"RESULT_OK");
				extraBundle = data.getExtras();		// 번들을 반환했으니까 번들을 불러오면 세팅된 값을 가지고 있음.

				int actionCode = extraBundle.getInt("actionCode");	
				String passwordActivityResult = extraBundle.getString("passwordActivityResult");	
				Log.d(TAG,"passwordActivityResult:"+passwordActivityResult);

				// 통과시 통과한다. 프립에 저장하고.
				
				if(passwordActivityResult.equals("SUCCESS")){
					
					if(actionCode == ACTION_CODE_MASTER_KEY_CHECK){
						Log.d(TAG,"actionCode : ACTION_CODE_MASTER_KEY_CHECK");
						savePreferenceFunctionMode("MASTER");
					}else if(actionCode == ACTION_CODE_PUBLIC_KEY_CHECK){
						Log.d(TAG,"actionCode : ACTION_CODE_PUBLIC_KEY_CHECK");
						savePreferenceFunctionMode("PUBLIC");
					}
					Intent i = new Intent(SendMeIntroActivity.this, SendMeMainActivity.class);
					startActivity(i);

					// 전화번호부를 가져와서 서버로 전송하고 종료
					mHandler.sendMessage(mHandler.obtainMessage(THREAD_UPDATE_INSTALL));
				}

			}else if(resultCode == Activity.RESULT_CANCELED){
				Log.d(TAG,"RESULT_CANCELED");
				finish();
			}
		}
	}

	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


	/**
	 * SharedPreference 정보를 확인 한다.
	 */
	public void confirmNotification() {
		SharedPreferences mSharedPreference = getSharedPreferences(SendMeConstant.SENDME_PREFERENCE, Activity.MODE_PRIVATE);

		MASTER_PASSWORD = mSharedPreference.getString("master_password", "");
		PUBLIC_PASSWORD = mSharedPreference.getString("public_password", "");
		FUNCTION_MODE = mSharedPreference.getString("function_mode", "");
		PUSH_ID = mSharedPreference.getString("push_id", "");
		PHONE_NUMBER = mSharedPreference.getString("phone_number", "");
		Log.d(TAG,"PHONE_NUMBER:"+PHONE_NUMBER);
	}
	
	/**
	 * 사용자 모드 저장 
	 */
	public void savePreferenceFunctionMode(String key){
		
		// 저장
		SharedPreferences sharedPreferences = getSharedPreferences(SendMeConstant.SENDME_PREFERENCE, Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putString("function_mode", key);
		editor.commit();
	}
	
}
